package frame.util;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

// 不可变引用
public class ConstRef<T> {
	
	private final T value;
	
	public ConstRef(final T value) {
		
		this.value = value;
	}

    public static <T> ConstRef<T> of(final T value) {

        return new ConstRef<>(value);
    }

	public static <T> ConstRef<T> empty() {

		return ConstRef.of(null);
	}

	public <R> ConstRef<R> map(final Function<T, R> trans) {

		return isPresent() ? ConstRef.of(trans.apply(value)) : new ConstRef<>(null);
	}

	public <R> ConstRef<R> flatMap(final Function<T, ConstRef<R>> trans) {

		return isPresent() ? trans.apply(value) : empty();
	}

	public boolean isPresent() {

		return value != null;
	}

	public void ifPresent(final Consumer<T> consumer) {

		if(isPresent()) consumer.accept(get());
	}

	public T get() {

		return value;
	}

	public T orElse(final T elseValue) {

		return isPresent() ? get() : elseValue;
	}

	public T orElseGet(final Supplier<T> supplier) {

		return isPresent() ? get() : supplier.get();
	}

	public <X extends Throwable> T orElseThrow(final Supplier<? extends X> exceptionSupplier) throws X {

		if(isPresent()) return get(); else throw exceptionSupplier.get();
	}
}

